<?php


namespace app\common\model\xiluedu;


use think\Model;

class CourseFree extends Model
{
    // 表名
    protected $name = 'xiluedu_course_free';

    // 追加属性
    protected $append = [
        'start_time_text',
        'end_time_text',
        'state'
    ];

    public function getStartTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['start_time']) ? $data['start_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i", $value) : $value;
    }


    public function getEndTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['end_time']) ? $data['end_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i", $value) : $value;
    }

    public function getStateAttr($value,$data){
        if($data['start_time'] > time()){
            return 2; //即将开始
        }else if($data['start_time'] < time()){
            return 1; //已经开始
        }else{
            return 0; //已经过期
        }
    }

    public static function getCourseByIds($course_ids){
        return Course::with(['teacher'])
                ->field('id,type,name,category_id,tag_ids,teacher_id,thumb_image,description,is_charge,(basic_num+real_num) total_num,collection_count,salesprice,play_count')
            ->where('id','in',$course_ids)
            ->where('status','1')
            ->order('weigh','asc')
            ->select();
    }

    /**
     *获取限免列表
     */
    public static function getCourseFree($user_id=NULL){
        $lists = static::where('end_time','gt',time())
            ->where('status','1')
            ->order('start_time','asc')
            ->limit(3)
            ->select();
        foreach ($lists as $row){
            $row->enroll_status = $user_id ? (CourseFreeEnroll::where('user_id',$user_id)->find()?1:0) : 0;
            $course = static::getCourseByIds($row->course_ids);
            $row->setAttr('course',$course);
        }
        return $lists;
    }

    //是否在免费课程中
    public static function isFree($course_id){
        return static::where('start_time','lt',time())
            ->where('end_time','gt',time())
            ->where('status','1')
            ->where("FIND_IN_SET(".(int)$course_id.",course_ids)")
            ->find()?1:0;
    }

}